import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Switch, Row, Col, Typography, App, Divider, Checkbox, Upload, Button, Avatar } from 'antd';
import { UserOutlined, MailOutlined, IdcardOutlined, EditOutlined, CheckCircleOutlined, LockOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import axios from 'axios';

const { Title } = Typography;

interface User {
    id: number;
    username: string;
    email: string;
    is_staff: boolean;
    is_active: boolean;
    is_superuser: boolean;
    profile: {
        nfc_card_id: string;
        avatar?: string;
    };
}

interface UserEditModalProps {
    visible: boolean;
    user: User | null;
    onCancel: () => void;
    onSuccess: () => void;
}

const UserEditModal: React.FC<UserEditModalProps> = ({
    visible,
    user,
    onCancel,
    onSuccess,
}) => {
    const { message, notification } = App.useApp();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [changePassword, setChangePassword] = useState(false);
    const [uploading, setUploading] = useState(false);
    const [avatarUrl, setAvatarUrl] = useState<string>('');
    const [previewUrl, setPreviewUrl] = useState<string>('');

    // 当用户数据变化时，更新表单
    useEffect(() => {
        if (user && visible) {
            form.setFieldsValue({
                username: user.username,
                email: user.email,
                nfc_card_id: user.profile?.nfc_card_id || '',
                is_active: user.is_active,
                is_staff: user.is_staff,
                is_superuser: user.is_superuser,
            });

            // 设置头像URL
            if (user.profile?.avatar) {
                const fullAvatarUrl = user.profile.avatar.startsWith('http')
                    ? user.profile.avatar
                    : `http://127.0.0.1:8000${user.profile.avatar}`;
                setAvatarUrl(fullAvatarUrl);
            } else {
                setAvatarUrl('');
            }
            setPreviewUrl(''); // 清除预览
        }
    }, [user, visible, form]);

    // 处理头像上传
    const handleAvatarUpload = async (file: File) => {
        if (!user) return false;

        const token = localStorage.getItem('adminAuthToken');
        if (!token) {
            message.error('请先登录');
            return false;
        }

        setUploading(true);

        const formData = new FormData();
        formData.append('avatar', file);

        try {
            const response = await axios.put(`/api/admin/users/${user.id}/update/`, formData, {
                headers: {
                    'Authorization': `Token ${token}`,
                    'Content-Type': 'multipart/form-data',
                }
            });

            if (response.data.profile?.avatar) {
                const fullAvatarUrl = response.data.profile.avatar.startsWith('http')
                    ? response.data.profile.avatar
                    : `http://127.0.0.1:8000${response.data.profile.avatar}`;
                setAvatarUrl(fullAvatarUrl);
                setPreviewUrl(''); // 清除预览，显示实际上传的头像

                message.success('头像更新成功！');

                // 通知父组件刷新用户列表
                onSuccess();
            }
        } catch (error: any) {
            console.error('Avatar upload error:', error);
            const errorMessage = error.response?.data?.error || '头像上传失败，请重试';
            message.error(errorMessage);
        } finally {
            setUploading(false);
        }

        return false; // 阻止默认上传行为
    };

    // 上传组件配置
    const uploadProps: UploadProps = {
        name: 'avatar',
        showUploadList: false,
        beforeUpload: (file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('只能上传 JPG/PNG 格式的图片!');
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小必须小于 2MB!');
                return false;
            }

            // 立即显示预览
            const reader = new FileReader();
            reader.onload = (e) => {
                const result = e.target?.result as string;
                setPreviewUrl(result);
            };
            reader.readAsDataURL(file);

            // 上传文件
            handleAvatarUpload(file);
            return false;
        },
    };

    const handleSubmit = async (values: any) => {
        if (!user) return;

        setLoading(true);
        const token = localStorage.getItem('adminAuthToken');

        // 如果不修改密码，移除密码相关字段
        const submitData = { ...values };
        if (!changePassword) {
            delete submitData.password;
            delete submitData.confirm_password;
        }

        try {
            await axios.put(`/api/admin/users/${user.id}/update/`, submitData, {
                headers: { 'Authorization': `Token ${token}` }
            });

            // 显示成功通知
            notification.success({
                message: '用户信息更新成功',
                description: `用户 "${values.username}" 的信息已成功更新`,
                placement: 'topRight',
                duration: 4,
                icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
            });

            onSuccess();
        } catch (error: any) {
            console.error('Failed to update user:', error);
            
            // 处理验证错误
            if (error.response?.data) {
                const errorData = error.response.data;

                // 如果是字段验证错误，显示具体错误信息
                if (typeof errorData === 'object' && !errorData.error) {
                    let hasFieldErrors = false;
                    Object.keys(errorData).forEach(field => {
                        const fieldErrors = errorData[field];
                        if (Array.isArray(fieldErrors)) {
                            form.setFields([{
                                name: field,
                                errors: fieldErrors
                            }]);
                            hasFieldErrors = true;
                        }
                    });

                    if (hasFieldErrors) {
                        message.error('请检查表单中的错误信息');
                    }
                } else {
                    // 显示错误通知
                    notification.error({
                        message: '更新用户失败',
                        description: errorData.error || '请检查输入信息是否正确',
                        placement: 'topRight',
                        duration: 6,
                    });
                }
            } else {
                notification.error({
                    message: '更新用户失败',
                    description: '网络错误或服务器异常，请稍后重试',
                    placement: 'topRight',
                    duration: 6,
                });
            }
        } finally {
            setLoading(false);
        }
    };

    const handleCancel = () => {
        form.resetFields();
        setChangePassword(false);
        setPreviewUrl('');
        onCancel();
    };

    return (
        <Modal
            title={
                <div style={{ textAlign: 'center' }}>
                    <EditOutlined style={{ marginRight: 8, color: '#1890ff' }} />
                    <Title level={4} style={{ margin: 0, display: 'inline' }}>
                        编辑用户信息
                    </Title>
                </div>
            }
            open={visible}
            onCancel={handleCancel}
            onOk={() => form.submit()}
            confirmLoading={loading}
            width={600}
            destroyOnHidden
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
            >
                <Divider orientation="left">用户头像</Divider>

                <Row gutter={16}>
                    <Col span={24}>
                        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
                            <Avatar
                                size={64}
                                src={previewUrl || avatarUrl}
                                icon={!previewUrl && !avatarUrl ? <UserOutlined /> : undefined}
                            />
                            <Upload {...uploadProps}>
                                <Button
                                    icon={<UploadOutlined />}
                                    style={{ marginLeft: 16 }}
                                    loading={uploading}
                                >
                                    {uploading ? '上传中...' : '修改头像'}
                                </Button>
                            </Upload>
                        </div>
                    </Col>
                </Row>

                <Divider orientation="left">基本信息</Divider>

                <Row gutter={16}>
                    <Col span={12}>
                        <Form.Item
                            name="username"
                            label="用户名"
                            rules={[
                                { required: true, message: '请输入用户名' },
                                { min: 3, message: '用户名至少3个字符' },
                                { max: 20, message: '用户名最多20个字符' },
                                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' }
                            ]}
                        >
                            <Input 
                                prefix={<UserOutlined />} 
                                placeholder="输入用户名"
                                autoComplete="off"
                            />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item
                            name="email"
                            label="邮箱地址"
                            rules={[
                                { required: true, message: '请输入邮箱地址' },
                                { type: 'email', message: '请输入有效的邮箱地址' }
                            ]}
                        >
                            <Input 
                                prefix={<MailOutlined />} 
                                placeholder="输入邮箱地址"
                                autoComplete="off"
                            />
                        </Form.Item>
                    </Col>
                </Row>



                <Form.Item
                    name="nfc_card_id"
                    label="NFC卡号"
                >
                    <Input
                        prefix={<IdcardOutlined />}
                        placeholder="输入NFC卡号（可选）"
                        autoComplete="off"
                    />
                </Form.Item>

                <Divider orientation="left">密码管理</Divider>

                <Row gutter={16}>
                    <Col span={24}>
                        <Form.Item>
                            <Checkbox
                                checked={changePassword}
                                onChange={(e) => {
                                    setChangePassword(e.target.checked);
                                    if (!e.target.checked) {
                                        // 清除密码字段
                                        form.setFieldsValue({
                                            password: '',
                                            confirm_password: ''
                                        });
                                    }
                                }}
                            >
                                修改用户密码
                            </Checkbox>
                        </Form.Item>
                    </Col>
                </Row>

                {changePassword && (
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="password"
                                label="新密码"
                                rules={[
                                    { required: changePassword, message: '请输入新密码' },
                                    { min: 6, message: '密码至少6个字符' }
                                ]}
                            >
                                <Input.Password
                                    prefix={<LockOutlined />}
                                    placeholder="输入新密码"
                                    autoComplete="new-password"
                                />
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item
                                name="confirm_password"
                                label="确认新密码"
                                dependencies={['password']}
                                rules={[
                                    { required: changePassword, message: '请确认新密码' },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (!changePassword || !value || getFieldValue('password') === value) {
                                                return Promise.resolve();
                                            }
                                            return Promise.reject(new Error('两次输入的密码不一致'));
                                        },
                                    }),
                                ]}
                            >
                                <Input.Password
                                    prefix={<LockOutlined />}
                                    placeholder="再次输入新密码"
                                    autoComplete="new-password"
                                />
                            </Form.Item>
                        </Col>
                    </Row>
                )}

                <Divider orientation="left">权限设置</Divider>

                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item
                            name="is_active"
                            label="账户状态"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="激活" 
                                unCheckedChildren="停用" 
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="is_staff"
                            label="管理员权限"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="是" 
                                unCheckedChildren="否" 
                            />
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item
                            name="is_superuser"
                            label="超级管理员"
                            valuePropName="checked"
                        >
                            <Switch 
                                checkedChildren="是" 
                                unCheckedChildren="否" 
                                disabled={user?.is_superuser && !user?.is_superuser} // 防止普通管理员修改超级管理员权限
                            />
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
        </Modal>
    );
};

export default UserEditModal;
